<!--售后订单管理-换货单-待确认 -->
<template>
  <div class="wait-exchange-confirm">
    <div class="title">
      <h1>申请换货</h1>
    </div>
    <div class="block">
      <header>
        <h2>
          1、供应商及产品线
        </h2>
      </header>
      <section>
        <el-form inline>
          <el-form-item label="供应商：">
            <span class="text">{{ render_data.orderData.vendorName || '~ ~' }}</span>
          </el-form-item>
        </el-form>
        <el-form inline>
          <el-form-item label="厂家：">
            <span class="text">{{ render_data.orderData.supplierName || '~ ~' }}</span>
          </el-form-item>
          <el-form-item label="产品线：">
            <span class="text">{{ render_data.orderData.productLineName || '~ ~' }}</span>
          </el-form-item>
          <el-form-item label="业务类型：">
            <span class="text">{{ render_data.orderData.businessModel || '~ ~' }}</span>
          </el-form-item>
          <el-form-item label="市场渠道：">
            <span class="text">{{ render_data.orderData.marketDesc || '~ ~' }}</span>
          </el-form-item>
          <el-form-item label="有效期至：">
            <span class="text">{{ render_data.orderData.contractInvalidDate || '~ ~' }}</span>
          </el-form-item>
        </el-form>
      </section>
    </div>
    <div class="block">
      <header>
        <h2>
          2、订单类型
        </h2>
      </header>
      <section>
        <el-form>
          <el-form-item>
            <span class="text">{{ render_data.orderData.orderTypeName || '~ ~' }}</span>
          </el-form-item>
        </el-form>
      </section>
    </div>
    <div class="block">
      <header>
        <h2>
          3、退货产品
        </h2>
      </header>
      <section class="return-product-table">
        <el-editable
          ref="returnProducts"
          v-loading="status.loading.return_products"
          height="400"
          :need-pagination="true"
          :columns="render_data.return_product.columns"
          :payload="render_data.return_product.data"
          @reload="getEchoReturnProductList"
        />
      </section>
    </div>
    <div class="block">
      <exchange-products-list
        ref="exchangeProductsList"
        :step-one-form-data="components_data"
        :products.sync="submit_data.exchange_product.data"
        @getBackExchangeGoods="getCbExchangeGoodsRows"
      >
        4、新换产品
      </exchange-products-list>
    </div>
    <div class="block">
      <reason
        :edit="false"
        :required="false"
        :reason-sel.sync="submit_data.return_reason.reason_sel"
        :reason-text.sync="submit_data.return_reason.reason_text"
        :reason-imgs.sync="submit_data.return_reason.reason_imgs"
      >
        5、退货原因
      </reason>
    </div>
    <div class="block">
      <header>
        <h2 class="required">
          6、承运方式
        </h2>
      </header>
      <section>
        <el-form>
          <el-form-item>
            <el-radio-group v-model="submit_data.carryway_id">
              <el-radio v-for="item in render_data.rows_carryway" :key="item.enumKey" :label="item.enumKey">
                {{ item.enumVal }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </section>
    </div>
    <div class="block">
      <address-func
        :address-id.sync="render_data.address_id"
        :is-edit="status.isEdit"
        @change-address="getCbSeledAddress"
      >
        <template #title>
          7、收货地址
        </template>
      </address-func>
    </div>
    <!-- 供应商拒收部分产品提示 -->
    <el-dialog title="提示" @close="onReceivedInfo" :visible.sync="status.visible.supplier_refuse" width="30%">
      <p>
        供应商拒收了部分退货产品，请根据供应商收到的退货产品重新修改新换产品。
      </p>
      <p>拒收的产品信息请查看相关退货单。</p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onReceivedInfo">知道了</el-button>
      </span>
    </el-dialog>
    <!-- 提交二次确认 -->
    <el-dialog title="提示" :visible.sync="status.visible.submit_confirm" width="30%">
      <span>确认提交订单？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="status.visible.submit_confirm = false">取 消</el-button>
        <el-button type="primary" :disabled="status.loading.submit" :loading="status.loading.submit" @click="onSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  salesReturnDetails,
  queryOrderInfo,
  actualReturnedProduct,
  echoExchangeProductList,
  downloadFailUploadDataHH,
  uploadReturnedExchangeProduct,
  submitOrderChangeConfirm
} from '@api/m_mall_web_v1.js';
import { RETURN_PRODUCTS_COLUMNS } from './const.js';
import { throttle } from 'lodash';
import ElEditable from '@components/el-editable';
import { exchangeProductsList } from '~/components/after-sale/exchange-products-list';
import reason from '~/components/after-sale/reason/index.vue';
import addressFunc from '~/components/after-sale/address-func/index.vue';
import { IndexService } from './index.service';
let indexService = new IndexService();
export default {
  name: 'WaitExchangeConfirm',
  components: { ElEditable, exchangeProductsList, reason, addressFunc },
  inject: ['apiMMallWeb'],
  provide: {
    downloadFailUploadDataHH: downloadFailUploadDataHH,
    uploadExchangeProduct: uploadReturnedExchangeProduct,
    exTemplateDownLoad:
      'https://md.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/9ds2jnta6w6693lv5j57n5328twi2srl.xlsx'
  },
  data() {
    return {
      submit_data: {
        queryOrderData: {},
        exchange_product: {
          data: []
        },
        return_reason: {
          reason_sel: '',
          reason_text: '',
          reason_imgs: []
        },
        carryway_id: '',
        seled_full_address: {}
      },
      render_data: {
        orderData: {
          vendorName: '',
          supplierName: '',
          businessModel: '',
          contractInvalidDate: '',
          productLineName: '',
          contractName: '',
          marketDesc: '',
          orderTypeName: ''
        },
        return_product: {
          columns: RETURN_PRODUCTS_COLUMNS,
          data: {}
        },
        rows_carryway: [],
        address_id: ''
      },
      //整合给组件使用的数据
      components_data: {
        // 给exchange-products-list组件使用的
        return_goods: [],
        exchange_goods: [],
        contract_data: {},
        supplier_data: {}
      },
      status: {
        isEdit: false,
        visible: {
          supplier_refuse: false,
          submit_confirm: false
        },
        loading: {
          submit: false,
          return_products: false
        }
      },
      idKeys: {
        orderCodeReturn: '',
        orderCode: '',
        orderDetailId: '',
        orderId: ''
      }
    };
  },
  watch: {
    'submit_data.exchange_product.data': {
      handler(nv, ov) {
        this.components_data.exchange_goods = nv;
      }
    }
  },
  computed: {
    // 获取路由参数
    routeParams() {
      return {
        orderId: this.$route.query.orderId
      };
    }
  },
  created() {
    // this.getDetailsData();
    this.initGlobalBtn();
    this.getCarryWayRows();
    if (this.routeParams.orderId) this.getOrderDetailInfo();
  },
  methods: {
    getOrderDetailInfo() {
      this.$axios({
        method: 'post',
        url: queryOrderInfo,
        data: {
          orderId: this.routeParams.orderId
        }
      }).then(res => {
        let result = res.data.payload;
        this.submit_data.queryOrderData = result;
        this.idKeys.orderCodeReturn = result.orderCodeReturn;
        this.idKeys.orderCode = result.orderCode;
        this.idKeys.orderDetailId = result.orderDetailId;
        this.idKeys.orderId = result.orderId;
        this.getEchoReturnProductList({ number: 1, size: 20 });
        this.reRenderPage(result);

        this.getDetailData(result);
      });
    },
    getDetailData(result) {
      // 编辑模式
      this.$axios({
        url: salesReturnDetails,
        method: 'post',
        data: {
          orderId: result.orderIdReturn
        }
      }).then(res => {
        let result = res.data.payload ? res.data.payload : {};
        console.log(result);
        // this.getOrderTypeRowsByEdit(result);
        // 设置退货原因
        this.submit_data.return_reason.reason_sel =
          result.orderData.returnReasonCode;
        this.submit_data.return_reason.reason_text =
          result.orderData.returnReasonDetail;
        this.submit_data.return_reason.reason_name =
          result.orderData.returnReasonName;
        this.submit_data.return_reason.reason_imgs = result.commonFile.map(
          item => item.fileUrl
        );
        // 设置供应商拒收部分退货字段"1"是没有，"2"是有
        this.status.visible.supplier_refuse =
          result.flag === '2' ? true : false;
        // 获取退货产品
      });
    },
    reRenderPage(result) {
      this.render_data.orderData = result;
      // 设置详情静态字段
      this.render_data.orderData = {
        vendorName: result.supplierVo.vendorName,
        supplierName: result.contractVo.supplierName,
        businessModel: result.contractVo.businessModel,
        contractInvalidDate: result.contractVo.contractInvalidDate || '',
        productLineName: result.contractVo.productLineName,
        contractName: result.contractVo.contractName,
        marketDesc: result.contractVo.marketDesc,
        orderTypeName: result.orderTypeName
      };
      // 设置承运方式
      this.submit_data.carryway_id = String(result.transportType);
      // 设置地址
      this.render_data.address_id = result.addressResDto.userAddressId;
      this.submit_data.seled_full_address = result.addressResDto;
      // 给exchange组件设置数据
      this.components_data.contract_data = result.contractVo;
      this.components_data.supplier_data = result.supplierVo;
    },

    getEchoReturnProductList(pager) {
      this.status.loading.return_products = true;
      this.$axios({
        method: 'post',
        url: actualReturnedProduct,
        data: {
          orderCode: this.idKeys.orderCodeReturn,
          flag: '1',
          page: pager.number,
          pageSize: pager.size
        }
      })
        .then(res => {
          let data = res?.data.payload;
          this.render_data.return_product.data = data;
          this.render_data.return_product.data.content = this.render_data.return_product.data.content.map(
            it => {
              return {
                ...it,
                attribute1: it.model || it.specs,
                productUnitName: it.productUnit,
                productCount: Number(it.returnQuantity) || 1,
                staticProductCount: Number(it.returnQuantity) || 1, // 这个字段，是用于products-list组件中，更换数量时拦截回归数据使用
                returnCount: Number(it.returnableQuantity),
                referencePrice: it.productPrice,
                mixsIds:
                  it.orginalOrderCode +
                  it.seqNo +
                  it.productCode +
                  it.batchNo +
                  it.validDate +
                  it.referrencePrice
              };
            }
          );

          this.getEchoExchangeProductList(
            this.render_data.return_product.data.content
          );
          //  设置exchange组件的return_goods字段
          this.components_data.return_goods = res?.data?.payload?.content || [];
        })
        .finally(() => {
          this.status.loading.return_products = false;
        });
    },
    getEchoExchangeProductList(returnGoods) {
      this.$axios({
        method: 'post',
        url: echoExchangeProductList,
        data: {
          orderCode: this.idKeys.orderCode,
          returnProductList: returnGoods.map(it => {
            return {
              productName: it.productName,
              returnQuantity: it.returnQuantity
            };
          })
        }
      }).then(res => {
        let data = res.data.payload?.content;
        this.submit_data.exchange_product.data = data.map(it => {
          return {
            ...it,
            attribute1: it.model || it.specs,
            productUnitName: it.productUnit,
            productCount: Number(it.exchangeQuantity),
            exhcangeCount: Number(it.exchangeableQuantity),
            referencePrice: it.productPrice,
            mixsIds: it.productCode
          };
        });
        this.components_data.exchange_goods =
          this.submit_data.exchange_product.data || [];

        this.setInitialProductsDataNums();
      });
    },
    setInitialProductsDataNums() {
      let exProductNamesNum = this.$refs.exchangeProductsList.concatCommonNameProduct(
        this.submit_data.exchange_product.data,
        'productCount'
      );
      let returnGoodsCurNums = this.$refs.exchangeProductsList.concatCommonNameProduct(
        this.render_data.return_product.data.content,
        'productCount'
      );
      // 初始化可选数量
      returnGoodsCurNums.forEach(rGood => {
        this.submit_data.exchange_product.data.forEach(item => {
          if (item.productName === rGood.name) {
            this.$set(item, 'optionalQuantity', rGood.commonNameTotalNum);
          }
        });
      });
      // 初始化已选数量
      this.submit_data.exchange_product.data.forEach(item => {
        this.$set(item, 'selectedQuantity', 0);
        exProductNamesNum.forEach(exGood => {
          if (item.productName === exGood.name) {
            this.$set(item, 'selectedQuantity', exGood.commonNameTotalNum);
          }
        });
      });
    },
    //   打开提交二次确认弹窗
    onShowComfirmDialog() {
      let verify_result = indexService.verifyStep(1, this.submit_data);
      if (verify_result.pass === true) {
        if (
          this.isSubmitProductsMatchRules(
            this.render_data.return_product.data.content,
            this.submit_data.exchange_product.data
          )
        ) {
          this.$message({
            type: 'error',
            message: '换货数量不正确'
          });
          return;
        }
        this.status.visible.submit_confirm = true;
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verify_result.message
        });
      }
    },
    isSubmitProductsMatchRules(returnGoods, exchangeGoods) {
      // 需要把双方的同名的整合到一起再做对比
      let rGoods = this.$refs.exchangeProductsList.concatCommonNameProduct(
        returnGoods,
        'productCount'
      );
      let exGoods = this.$refs.exchangeProductsList.concatCommonNameProduct(
        exchangeGoods,
        'productCount'
      );
      let hahaArr = [];
      rGoods.forEach(r => {
        let obj = {
          name: '',
          rNum: 0,
          eNum: 0
        };
        obj.name = r.name;
        obj.rNum = r.commonNameTotalNum;
        exGoods.forEach(curGoods => {
          if (r.name === curGoods.name) {
            obj.eNum = curGoods.commonNameTotalNum;
          }
        });
        hahaArr.push(obj);
      });
      let flag = hahaArr.some(item => {
        return item.eNum !== item.rNum;
      });
      return flag;
    },
    onReceivedInfo() {
      // 清空换货数据
      this.submit_data.exchange_product.data = [];
      this.status.visible.supplier_refuse = false;
    },
    restructSubmitData() {
      return Object.assign(this.submit_data.queryOrderData, {
        addressResDto: this.submit_data.seled_full_address,
        saveProductVOChange: this.submit_data.exchange_product.data,
        transportType: this.submit_data.carryway_id,
        saveProductVO: this.render_data.return_product.data.content
      });
      // return {
      //   orderId: this.idKeys.orderId,
      //   orderCode: this.idKeys.orderCode,
      //   returnReason: this.submit_data.return_reason.reason_sel,
      //   returnReasonDetail: this.submit_data.return_reason.reason_text,
      //   commonFileForms: this.submit_data.return_reason.reason_imgs.map(item => {
      //     let name = item.substring(item.lastIndexOf('/') + 1);
      //     return {
      //       fileName: name.split('.')[0],
      //       fileType: name.split('.')[1],
      //       fileUrl: item
      //     };
      //   }) // 原因图片
      // };
    },
    // 真正的提交
    onSubmit: throttle(
      function() {
        this.status.loading.submit = true;
        this.$axios({
          method: 'post',
          url: submitOrderChangeConfirm,
          data: this.restructSubmitData()
        })
          .then(res => {
            if (res.data.code === '0') {
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$router.push('/after-sale/order-management');
            }
          })
          .finally(() => {
            this.status.loading.submit = false;
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    getCbExchangeGoodsRows(goods) {
      this.submit_data.exchange_product.data = goods;
    },
    // 获取回调的完整地址数据
    getCbSeledAddress(val) {
      this.submit_data.seled_full_address = val;
    },
    // 获取承运方式数据
    async getCarryWayRows() {
      this.render_data.rows_carryway = await this.apiMMallWeb.CommonEnumOrderV1ApiPOST(
        {
          query: {
            indexCode: 'transportType'
          }
        }
      );
    },
    // 初始化全局按钮
    initGlobalBtn() {
      let btnObj = {
        type: 'btn',
        arr: []
      };
      let submitBtn = {
        type: 'primary',
        val: '确认提交',
        handle: this.onShowComfirmDialog
      };
      btnObj.arr.push(submitBtn);
      this.$store.commit('changeLayoutHandle', btnObj);
    }
  }
};
</script>
<style lang="less">
.wait-exchange-confirm {
  background-color: #f7f8fa !important;
  margin: 0 !important;
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  .return-product-table,
  .other-info-part {
    height: 400px;
    display: flex;
  }
  .other-info-part {
    flex-direction: column;
  }
  .title {
    background-color: #fff;
    margin: 0 -0 10px 0;
    padding: 20px;
  }
  header {
    padding: 12px 16px;
    border-bottom: 1px solid #eef0f5;
    display: flex;
  }
  section {
    padding: 20px 16px;
  }
  .required:before {
    content: '*';
    position: relative;
    color: red;
  }
  .text {
    font-weight: 900;
  }
  .right {
    text-align: right;
  }
  .w100p {
    width: 100%;
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}
</style>
